package org.lee.other.opt.service;

import org.lee.other.opt.Employee;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * EmployeeService
 *
 * @author dralee
 * @date 2022-01-22 13:57:47
 **/
public class EmployeeService implements IEmployeeService {

    private List<Employee> employees;

    public EmployeeService() {
        employees = new ArrayList<Employee>() {{
            add(new Employee(1, "Kate", 12345));
            add(new Employee(2, "Merry", 13345));
            add(new Employee(3, "Jim", 12545));
            add(new Employee(4, "Tom", 12645));
            add(new Employee(5, "Frank", 13335));
        }};

    }

    @Override
    public Optional<Employee> findById(int id) {
        return employees.stream().filter(e -> e.getId() == id).findFirst();
    }

    @Override
    public List<Employee> findByIds(List<Integer> ids) {
        return ids.stream()
                .map(this::findById)
                .filter(Optional::isPresent)
                .map(Optional::get).collect(Collectors.toList());
    }

    @Override
    public List<Employee> findByIds2(List<Integer> ids) {
        return ids.stream()
                .map(this::findById)
                .flatMap(opt -> opt.map(Stream::of).orElseGet(Stream::empty))
                .collect(Collectors.toList());
    }
}
